var JargonToolbar = {
	
	onmenuitemEnable : function()
	{
		JargonCommon.Logger.log('onmenuitemEnable()');
		var btnEnable = document.getElementById('jargonMiEnable');
		var checked = btnEnable.getAttribute('checked');
		if (!checked)
		{
			checked = false;
		}
		JargonCommon.isEnabled = checked;
		JargonCommon.Preferences.setBoolPref(JargonCommon.Preferences.isEnabled, !!checked);
		JargonCommon.Logger.log('isEnabled = ' + JargonCommon.Preferences.getBoolPref(JargonCommon.Preferences.isEnabled));
		
		setToolbarEnabled(checked);
	},
	
	onmenuitemOptions : function()
	{
		window.openDialog('chrome://jargon/content/options.xul', 'jargonOptionsDialog', 'modal');
	},
	
	onPageLoad : function()
	{
		// page load event
	},
	
	onBeforeNavigate : function()
	{
		alert('before navigate');
	},
		
	getJargonForSite : function(hostname)
	{
		JargonCommon.Logger.log('getJargonForSite(\'' + hostname + '\')');
		var jargon = null;
		var jargonList = JargonCommon.siteJargons.split(';');
		for (var i = 0; i < jargonList.length; i++)
		{
			var entry = jargonList[i].split(',');
			if (JargonCommon.areSitesEqual(entry[0], hostname))
			{
				jargon = entry[1];
			}
		}
		return jargon;
	},
	
	updatePanel : function(host, jargonForSite, languages)
	{
		JargonCommon.Logger.log('updatePanel(' + host + ',' + jargonForSite + ',' +languages + ')');
		document.getElementById('jargon-lblDomain').value = host;
		var currentLanguage = jargonForSite;
		if (!currentLanguage)
		{
			currentLanguage = languages.split(',')[0];
		}
		document.getElementById('jargon-lblJargon').value = currentLanguage;
	},
	
	onHttpRequest : function(httpChannel)
	{
		JargonCommon.Logger.log('onHttpRequest()');
		var host = httpChannel.getRequestHeader('Host');
		var languages = httpChannel.getRequestHeader('Accept-Language');
		var jargonForSite = JargonToolbar.getJargonForSite(host);
		JargonCommon.Logger.log('\tjargon for site \'' + host + '\' is \'' + jargonForSite + '\'');
		if (!!jargonForSite)
		{
			httpChannel.setRequestHeader('Accept-Language', jargonForSite, false);
			JargonCommon.Logger.log('\tsetting language to ' + jargonForSite);
		}
		JargonToolbar.updatePanel(host, jargonForSite, languages);
	},

	setToolbarEnabled : function(enabled)
	{
		JargonCommon.Logger.log('setToolbarEnabled(' + enabled + ')');
		if (enabled)
		{
			Observer.register();
			Observer.onHttpRequest = this.onHttpRequest;
		}
		else
		{
			Observer.unregister();
		}
	},
	
	init : function()
	{
		var browser = getBrowser();
		JargonCommon.Logger.log('initializing JargonToolbar');
	
		var enabled = JargonCommon.Preferences.getBoolPref(JargonCommon.Preferences.isEnabled);
		this.setToolbarEnabled(enabled);
		
		browser.addEventListener('pageshow', this.onPageLoad, true);
		browser.addEventListener('beforenavigate', this.onBeforeNavigate, true);
	}
};

JargonToolbar.init();